package org.alipay4j.model.sns;

import java.util.Date;

import org.alipay4j.AlipayException;
import org.alipay4j.http.Response;

import com.alibaba.fastjson.JSONObject;

/**
 * 网页授权对象
 *
 * @author yangqisheng
 * @since 0.1.0
 */
public final class SnsAccessToken {
	
	private String user_id;
    private String access_token;
    private int expires_in = 3600;
    private String refresh_token;
    private long exprexpired_time;

    /**
     * 通过输出对象，从输出对象转换为JSON对象，后获取JSON数据包
     *
     * <p>
     * 正常情况下，支付宝会返回下述JSON数据包给公众号：
     * {"userid":"2088102150477652","expires_in":3600,"refresh_token":"20120823ac6ffaa4d2d84e7384bf983531473993","access_token":"20120823ac6ffaa4d2d84e7384bf983531473993"}</p>
     *
     * @param response 输出对象
     * @throws org.weixin4j.AlipayException 支付宝操作异常
     */
    public SnsAccessToken(Response response) throws AlipayException {
        this(response.asJSONObject());
    }

    /**
     * 通过支付宝公众平台返回JSON对象创建凭证对象
     *
     * <p>
     * 正常情况下，支付宝会返回下述JSON数据包给公众号：
     * {"userid":"2088102150477652","expires_in":3600,"refresh_token":"20120823ac6ffaa4d2d84e7384bf983531473993","access_token":"20120823ac6ffaa4d2d84e7384bf983531473993"}</p>
     *
     * @param jsonObj JSON数据包
     * @throws org.alipay4j.AlipayException 支付宝操作异常
     */
    public SnsAccessToken(JSONObject jsonObj) throws AlipayException {
        this.access_token = jsonObj.getString("access_token");
        this.expires_in = jsonObj.getIntValue("expires_in");
        this.refresh_token = jsonObj.getString("refresh_token");
        this.user_id = jsonObj.getString("user_id");
        //设置下次过期时间 = 当前时间 + (凭证有效时间(秒) * 1000)
        this.exprexpired_time = new Date().getTime() + (this.expires_in * 1000);
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    /**
     * 判断用户凭证是否过期
     *
     * @return 过期返回 true,否则返回false
     */
    public boolean isExprexpired() {
        Date now = new Date();
        long nowLong = now.getTime();
        return nowLong > exprexpired_time;
    }

    /**
     * 将数据转换为JSON数据包
     *
     * @return JSON数据包
     */
    @Override
    public String toString() {
        return "{\"user_id\":\"" + this.getUser_id()
                + "\",\"expires_in\":" + this.getExpires_in()
                + ",\"refresh_token\":\"" + this.getRefresh_token()
                + "\",\"access_token\":\"" + this.getAccess_token() + "\"}";
    }

    public int getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(int expires_in) {
        this.expires_in = expires_in;
    }

    public String getRefresh_token() {
        return refresh_token;
    }

    public void setRefresh_token(String refresh_token) {
        this.refresh_token = refresh_token;
    }

	public String getUser_id() {
		return user_id;
	}

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

}
